package com.lishem.rpc.server.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class SentinelConfig {

    /**
     * 获取订单接口
     */
    private static final String GET_ORDER = "getOrder";

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    /**
     * 初始化限流规则
     * @throws Exception
     */
    @PostConstruct
    private void initFlowRules() throws Exception {
        FlowRule rule1 = new FlowRule();
        rule1.setResource(GET_ORDER);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setCount(1);   // 每秒调用最大次数为 1 次

        List<FlowRule> rules = new ArrayList<>();
        rules.add(rule1);

        // 将控制规则载入到 Sentinel
        FlowRuleManager.loadRules(rules);
    }

    /**
     * 初始化降级规则
     * @throws Exception
     */
    @PostConstruct
    private void initDegradeRules() throws Exception {
        // 创建规则集合
        List<DegradeRule> rules = new ArrayList<DegradeRule>();
        // 创建一个降级规则
        DegradeRule rule = new DegradeRule();
        // 设定一个KEY标识
        rule.setResource(GET_ORDER);
        //  降级的规则: 设置比率为10%
        rule.setCount(0.1);
        // 设置降级策略
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
        // 设定时间窗大小， 默认单位是秒
        rule.setTimeWindow(10);
        rules.add(rule);
        // 将控制规则载入到 Sentinel
        DegradeRuleManager.loadRules(rules);
    }
}